﻿using System.Security.Cryptography;
using System.Text;

namespace Nuclear.Utils;

public static class CryptoUtils
{
    private static DES CreateDesCryptoProvider(string key)
    {
        const int keyLength = 8;
        var bytes = new byte[keyLength];
        var keyBytes = Encoding.UTF8.GetBytes(key);
        for (int i = 0; i < keyLength; i++)
        {
            if (i < keyBytes.Length)
                bytes[i] = keyBytes[i];
            else
                bytes[i] = 0x01;
        }

#pragma warning disable S5547
        var des = DES.Create();
#pragma warning restore S5547
        des.Key = bytes;
        des.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
        des.Mode = CipherMode.ECB;

        return des;
    }

    public static string EncryptCrmebPassword(string password, string key)
    {
#pragma warning disable S5547
        using var des = CreateDesCryptoProvider(key);
#pragma warning restore S5547
#pragma warning disable S3329
        var encryptor = des.CreateEncryptor(des.Key, des.IV);
#pragma warning restore S3329
        var passwordBytes = Encoding.UTF8.GetBytes(password);
        var payload = encryptor.TransformFinalBlock(passwordBytes, 0, passwordBytes.Length);

        return Convert.ToBase64String(payload);
    }

    public static string DecryptCrmebPassword(string encryptedPassword, string key)
    {
#pragma warning disable S5547
        using var des = CreateDesCryptoProvider(key);
#pragma warning restore S5547
        var decryptor = des.CreateDecryptor(des.Key, des.IV);
        var passwordBytes = Convert.FromBase64String(encryptedPassword);
        var payload = decryptor.TransformFinalBlock(passwordBytes, 0, passwordBytes.Length);

        return Encoding.UTF8.GetString(payload);
    }
}